package com.easyaop.asm.bytecode.asm;

import com.easyaop.asm.bytecode.MethodInfo;
import lombok.Setter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;

public class RetAroundMethodVisitor extends MethodVisitor {
    @Setter
    private MethodInfo target;

    public RetAroundMethodVisitor(int api, MethodVisitor methodVisitor) {
        super(api, methodVisitor);
    }

    @Override
    public void visitInsn(int opcode) {
        if (opcode == Opcodes.ARETURN) {

            GeneratorAdapter targetAdapter = new GeneratorAdapter(mv, target.access, target.name, target.descriptor);

            Type returnType = Type.getReturnType(target.descriptor);
            switch (returnType.getSort()) {
                case Type.VOID:
                    mv.visitInsn(Opcodes.POP);
                    break;

                case Type.BOOLEAN:
                case Type.CHAR:

                case Type.BYTE:
                case Type.SHORT:
                case Type.INT:
                case Type.LONG:

                case Type.FLOAT:
                case Type.DOUBLE:
                    targetAdapter.unbox(returnType);
                    break;
                case Type.OBJECT:
                case Type.ARRAY:

                    targetAdapter.checkCast(returnType);
                    break;

            }
            targetAdapter.returnValue();
            return;
        }
        super.visitInsn(opcode);
    }
}
